package com.example.ai_agent.rag;

import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.document.Document;
import org.springframework.ai.reader.markdown.MarkdownDocumentReader;
import org.springframework.ai.reader.markdown.config.MarkdownDocumentReaderConfig;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Yan.z.h
 * @version 1.0
 */
@Component
@Slf4j
public class LoveAppDocumentLoader {
    private  final ResourcePatternResolver resourcePatternResolver;


    public LoveAppDocumentLoader(ResourcePatternResolver resourcePatternResolver) {
        this.resourcePatternResolver = resourcePatternResolver;
    }

    /**
     * 加载所有的markDown 文件
     * @return
     */
    public List<Document> getALlDocement(){
        ArrayList<Document> allDocument = new ArrayList<>();
        try {
            Resource[] resources = resourcePatternResolver.getResources("classpath:/document/*.md");
            for (Resource resource:resources) {
                String filename = resource.getFilename();
                String status = filename.substring(filename.length() - 6, filename.length() - 4);


                MarkdownDocumentReaderConfig config = MarkdownDocumentReaderConfig.builder()
                        .withHorizontalRuleCreateDocument(true)
                        .withIncludeCodeBlock(false)
                        .withIncludeBlockquote(false)
                        .withAdditionalMetadata("filename", filename)
                        .withAdditionalMetadata("status", status)
                        .build();
                MarkdownDocumentReader markdownDocumentReader = new MarkdownDocumentReader(resource, config);
                allDocument.addAll(markdownDocumentReader.get());

            }
        } catch (IOException e) {
            log.error("markDown 文件加载失败",e);
        }
        return allDocument;

    }
}
